package com.financing.wap.web.controller.api;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.financing.wap.common.CommonConstantUtil;
import com.financing.wap.common.ResultMap;
import com.financing.wap.common.ResultMap.STATUS;
import com.financing.wap.common.Session;
import com.financing.wap.common.Views;
import com.financing.wap.dto.AuthenticationDTO;
import com.financing.wap.dto.FaUserDTO;
import com.financing.wap.dto.FaUserWechatDTO;
import com.financing.wap.dto.FpShopActivityUserDTO;
import com.financing.wap.dto.RegisterDTO;
import com.financing.wap.dto.ShopperUserInfoDTO;
import com.financing.wap.dto.UserDTO;
import com.financing.wap.service.IAuthenticationService;
import com.financing.wap.service.ICheckCodeService;
import com.financing.wap.service.IFpShopActivityUserService;
import com.financing.wap.service.IRegisterService;
import com.financing.wap.service.IShopperUserInfoService;
import com.financing.wap.service.ISmsService;
import com.financing.wap.service.IUserService;
import com.financing.wap.service.IUserWechatService;
import com.financing.wap.util.BasicUtils;
import com.financing.wap.util.Constants;
import com.financing.wap.util.DateUtil;
import com.financing.wap.util.IPUtil;
import com.financing.wap.util.MemcacheCacheHelper;
import com.financing.wap.util.PropertiesUtils;
import com.financing.wap.util.SecureUtil;
import com.financing.wap.util.StringUtil;
import com.financing.wap.web.controller.BaseController;

@Controller("apiLoginController")
@RequestMapping("/api")
public class LoginController extends BaseController {

	@Autowired
	private IUserService userService;

	@Autowired
	private IUserWechatService userWechatServiceImpl;

	@Autowired
	public IAuthenticationService authenticationService;

	@Autowired
	private IFpShopActivityUserService fpShopActivityUserService;

	@Autowired
	private ICheckCodeService checkCodeServiceImpl; // 短信验证码服务

	@Autowired
	private IRegisterService registerService;// 注册服务

	@Autowired
	public ISmsService smsService;// 注册服务

	@Autowired
	public IShopperUserInfoService shopperUserInfoService;

	@RequestMapping(value = "/login")
	@ResponseBody
	@SuppressWarnings(value = { "unchecked" })
	public ResultMap login(UserDTO user, HttpServletRequest request, HttpServletResponse response) {
		ResultMap result = new ResultMap();
		try {
			if(StringUtil.isNullOrEmptyNStr(user.getPassword(),user.getLoginName())){
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				result.setMessage("密码为空");
				return result;
			}
			// 对密码进行加密
			String password = user.getPassword();
			String securePassword = SecureUtil.MD5EncryptAndBase64(password);
			user.setPassword(securePassword);

			user = userService.getUserByUF(user);

			// 用户状态校验
			if (user == null) {
				// 已经被禁用
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_PWS_ERROR);
				result.setMessage("账户或密码错误");
				return result;
			}

			// 查询是否活动中
			String start = "2016-01-01 00:00:00";
			String end = "2017-10-20 23:59:59";
			// 判断时间
			Date inputDate = new Date();
			SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date d1 = sf.parse(start);
			Date d2 = sf.parse(end);
			// 在设定时间内
			if (inputDate.before(d2) && inputDate.after(d1)
					&& (user.getRole() == null || !user.getRole().equals("2"))) {

				// 修改状态为通过
				UserDTO ud = new UserDTO();
				ud.setId(user.getId());
				ud.setuShoprole("2"); //
				ud.setFpTempRole("1"); // 活动通过标识
				user.setRole("2");
				ud.setLoginName(user.getLoginName());
				userService.updateUser(ud);
			}

			// 用户状态验证
			if (Constants.FA_STATUS_DISABLE.equals(user.getFaStatus())) {

				// 已经被禁用
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_ACCOUNT_DISABLE);
				result.setMessage("用户已经被禁用");
				return result;

			}
			// 用户状态验证
			if (Constants.FA_STATUS_BLACK.equals(user.getFaStatus())) {

				// 已经被禁用
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_ACCOUNT_BLACK);
				result.setMessage("用户已经被拉黑");
				return result;

			}

			boolean flagVistProjectInfo = false;
			try {
				java.sql.Date sqlDate = DateUtil.getSqlDate(CommonConstantUtil.DATE_SIMU);
				java.sql.Date createDate = DateUtil.toSqlDate(user.getCreateDate());
				if (createDate.before(sqlDate)) {// 今天注册前 都能访问
					flagVistProjectInfo = true;
				}
				// 添加活动临时标识判断
				// else if(user.getFpTempRole().equals("1")){
				// flagVistProjectInfo=true;
				//
				// }
				else {
					// 注册之后的 需要是否认证通过
					String role = user.getRole();
					boolean b = StringUtils.isNotBlank(role) && !role.equals("1") && !role.equals("98")
							&& !role.equals("99");
					if (b) {
						flagVistProjectInfo = true;
					}
				}
			} catch (Exception e1) {
				log.error("get flagVistProjectInfo error", e1);
			}
			result.setAttribute("flagVistProjectInfo", flagVistProjectInfo);

			Session session = getSession(true);
			session.setLogin(true);
			session.setUser(user);
			setSession(session);
			AuthenticationDTO auth = authenticationService.queryAuthInfo(user.getId());

			String returnUrl = (String) session.getAttribute("returnUrl");
			Map<String, Object> parameterMap = (Map<String, Object>) session.getAttribute("returnParameterMap");
			String returnMethod = (String) session.getAttribute("returnMethod");
			result.setAttribute("returnUrl", returnUrl);
			result.setAttribute("params", parameterMap);
			result.setAttribute("method", returnMethod);

			result.setAttribute("userType", user.getUType());
			result.setAttribute("uRole", user.getRole());
			result.setAttribute("uEmail", user.getuEmail());
			result.setAttribute("reviewStatus", "0");
			result.setAttribute("uRemark", user.getRemark());
			result.setAttribute("loginName", user.getLoginName());
			result.setAttribute("uRealName", user.getuRealName());
			result.setAttribute("cardAddress", user.getCardAddress());

			if (auth != null) {
				result.setAttribute("reviewStatus", auth.getReviewStatus());
				result.setAttribute("trade", auth.getTrade());
				result.setAttribute("tradeAge", auth.getTradeAge());
			}
			if (StringUtils.isBlank(user.getUserName())) {
				result.setAttribute("uName", "");
			} else {

				result.setAttribute("uName", user.getUserName());
			}

			// 查询店主个人信息
			try {
				ShopperUserInfoDTO shopperUserInfo = new ShopperUserInfoDTO();
				// 用户id
				shopperUserInfo.setUserId(user.getId());
				ShopperUserInfoDTO shopperUserInfoDto = shopperUserInfoService.queryListGetFirst(shopperUserInfo);
				result.setAttribute("shopperUserInfoDto", shopperUserInfoDto);
			} catch (Exception e) {
				log.error("get ShopperUserInfoDTO error", e);
			}

			FaUserDTO userTmp = new FaUserDTO();
			userTmp.setId(user.getId());
			userTmp.setLastLoginIP(IPUtil.getRemoteHost(request));
			userTmp.setLastLoginTime(new Date());
			userTmp.setLoginNum(user.getLoginNum() + 1);
			userTmp.setUpdateBy(user.getId());
			userService.updateFaUserInfo(userTmp);

			result.setAttribute("id", user.getId());
			result.setAttribute("lastLoginIP", user.getLastLoginIP());
			result.setAttribute("lastLoginTime", user.getLastLoginTime());
			result.setAttribute("uImage", user.getuImage());

			String pt = request.getParameter(Constants._PT);
			if (StringUtil.isMobilePT(pt)) {
				String token = user.getId();
				try {
					String sessionId = request.getRequestedSessionId();
					token = SecureUtil.encrypt(token).replaceAll("=", "");
					Cookie cookie = new Cookie(Constants._TOKEN, token);
					cookie.setMaxAge(60 * 60 * 24 * 15);
					cookie.setPath("/");
					response.addCookie(cookie);
					// android
					result.setAttribute("token", token);
					result.setAttribute("phoneid", sessionId);
					log.info("MemcacheCacheHelper.mcc.set token:" + token);
					MemcacheCacheHelper.mcc.set(token, System.currentTimeMillis(), 0);
				} catch (Exception e) {
					log.error("mobile pt create token error!", e);
				}
			}

			// wap_jee_1.1 加入微信信息
			FaUserWechatDTO faUserWechatDTO = new FaUserWechatDTO();
			faUserWechatDTO.setUserId(user.getId());
			faUserWechatDTO = userWechatServiceImpl.queryUserWechatInfo(faUserWechatDTO);
			if (faUserWechatDTO != null) {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("headimgurl", faUserWechatDTO.getHeadimgurl());
				map.put("nickname", faUserWechatDTO.getNickname());
				result.setAttribute("faUserWechatDTO", map);
			}

			result.setStatus(STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setMessage("登陆成功");

		} catch (Exception e) {
			log.error("login error", e);
		}
		result.setAttribute("className", LoginController.class.getName());
		result.setAttribute("methodName", "login");
		return result;
	}

	/**
	 * 放射 wap 过滤数据
	 * 
	 * @param jsons
	 * @return
	 */
	public String waplogin(String jsons) {
		try {
			JSONObject json = JSON.parseObject(jsons);

			// 获取 类名 方法名 进行放射
			JSONObject jo = json.getJSONObject("attributes");
			// 进行 多余字段过滤的数据
			jo.remove("uEmail");
			jo.remove("uRemark");
			jo.remove("uRole");
			jo.remove("lastLoginTime");
			jo.remove("trade");
			jo.remove("tradeAge");
			jo.remove("lastLoginIP");
			jo.remove("userType");
			return json.toJSONString();
		} catch (Exception e) {
			log.error("error  WAPlogin:", e);
			return jsons;
		}
	}

	@RequestMapping(value = "/logout")
	@ResponseBody
	public ResultMap logout(HttpServletRequest request, HttpServletResponse response) {
		ResultMap result = new ResultMap();
		Session session = getSession(true);
		boolean login = session.getLogin();
		if (login == true) {
			session.setLogin(false);
			session.setUser(null);
		}
		String _tokenHead = "";
		request.getSession().invalidate();
		Cookie[] cookies = request.getCookies();
		for (int i = 0; i < cookies.length; i++) {
			if (Constants._TOKEN.equals(cookies[i].getName())) {
				_tokenHead = cookies[i].getValue();
			}
			Cookie cookie = new Cookie(cookies[i].getName(), null);
			cookie.setMaxAge(0);
			response.addCookie(cookie);
		}

		// 删除token 失效
		String pt = request.getParameter(Constants._PT);
		if (StringUtil.isMobilePT(pt)) {
			String token = request.getHeader("token");
			if (StringUtils.isBlank(token)) {
				token = _tokenHead;
			}
			log.info("loginOut token :" + token);
			if (StringUtils.isNotBlank(token))
				MemcacheCacheHelper.mcc.delete(token);
		}

		result.setStatus(STATUS.SUCCESS);
		result.setMessage("退出登陆成功");
		result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
		return result;
	}

	@RequestMapping(value = "/forget", method = RequestMethod.GET)
	public String forget(HttpServletRequest request) {

		/*
		 * SMSSendUtil u = new SMSSendUtil(); List l = new ArrayList();
		 * l.add("13795204024,15601730809"); try { u.sendSMS(l, "测试"); } catch
		 * (Exception e1) { e1.printStackTrace(); }
		 */

		return getTplPath(request) + Views.FORGET_PAGE;
	}

	/**
	 * 快捷登录
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/quickLogin")
	@ResponseBody
	@SuppressWarnings(value = { "unchecked" })
	public synchronized ResultMap quickLogin(HttpServletRequest request, HttpServletResponse response) {
		ResultMap result = new ResultMap();

		try {
			String loginName = request.getParameter("loginName");/// 登录名
			String validatecode = request.getParameter("validatecode");// 手机短信验证码
			String sourceMobile = request.getParameter("sourceMobile");// 来源手机
			String path = request.getParameter("pathToken"); // 二维码认证令牌
			
			String mediaSource = request.getParameter("mediaSource");

			// 检查数据是否为空
			if (BasicUtils.isEmpty(loginName, validatecode)) {
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				result.setMessage("参数缺失");
				return result;
			}

			// 判断活动认证
			boolean activityRole = false;

			// 时间区间设置
			String start = "2016-01-01 00:00:00";
			String end = "2017-10-20 23:59:59";
			// 判断时间
			Date inputDate = new Date();
			SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date d1 = sf.parse(start);
			Date d2 = sf.parse(end);

			// 判断二维码认证
			if (!StringUtils.isBlank(path) && path.equals("activityRole")) {
				// 在设定时间内
				if (inputDate.before(d2) && inputDate.after(d1)) {
					activityRole = true;
				}
			}

			// 1、，手机验证码
			if (checkCodeServiceImpl.CheckCodeSwitch()) {
				Integer activety_otp_time = new Integer(PropertiesUtils.getValue("activety_otp_time"));
				// 验证码超时
				if (checkOtpCodeTimeOut(loginName, activety_otp_time, ISmsService.OTP_CODE_FIRST_TIME)) {
					result.setStatus(ResultMap.STATUS.FAILE);
					result.setStatusCode(ResultMap.STATUS_CODE_OTP_VALIDATE_ERROR_TIMEOUT);
					result.setMessage("手机验证码超时！");
					return result;

				}
				;
				ResultMap resultOtp = checkOtpCode(loginName, validatecode);
				if (!STATUS.SUCCESS.equals(resultOtp.getStatus())) {
					result.setStatus(resultOtp.getStatus());
					result.setStatusCode(resultOtp.getStatusCode());
					result.setMessage(resultOtp.getMessage());
					return result;
				}
			}

			// 2、，是否注册
			boolean mobileRegistered = userService.isMobileRegistered(loginName);
			UserDTO user = new UserDTO();
			boolean isNewUser = false;
			if (!mobileRegistered) {
				RegisterDTO registerDto = new RegisterDTO();
				registerDto.setMobile(loginName);
				registerDto.setSourceMobile(sourceMobile);
				// 自动注册
				isNewUser = true;
				// String pwd="sfa"+RandomUtils.getRandomUtils(6);
				// log.debug(loginName+"自动生成密码:"+pwd);
				// registerDto.setPassword(pwd); //需求不需要自动生成密码
				// 判断活动传入
				if (activityRole) {
					registerDto.setuShoprole("2");
					registerDto.setFpTempRole("1"); // 活动通过标识
					// 添加抽奖名单
					FpShopActivityUserDTO fsau = new FpShopActivityUserDTO();
					fsau.setMobile(loginName);
					int fsauNum = fpShopActivityUserService.queryListCount(fsau);
					if (fsauNum == 0) {
						fpShopActivityUserService.insert(fsau);
					}

				}
				//设置媒体来源
				registerDto.setMediaSource(mediaSource);
				
				// 未注册 自动注册
				UserDTO userLogin = registerService.doRegister(registerDto);
				result.setAttribute("uImage", userLogin.getuImage());
				result.setAttribute("isNewUser", isNewUser);
				boolean flagVistProjectInfo = false;
				try {
					java.sql.Date sqlDate = DateUtil.getSqlDate(CommonConstantUtil.DATE_SIMU);
					java.sql.Date createDate = DateUtil.toSqlDate(user.getCreateDate());
					if (createDate.before(sqlDate)) {// 今天注册前 都能访问
						flagVistProjectInfo = true;
					} else {
						// 注册之后的 需要是否认证通过
						String role = user.getRole();
						boolean b = StringUtils.isNotBlank(role) && !role.equals("1") && !role.equals("98")
								&& !role.equals("99");
						if (b) {
							flagVistProjectInfo = true;
						}
					}
				} catch (Exception e1) {
					log.error("get flagVistProjectInfo error", e1);
				}
				result.setAttribute("flagVistProjectInfo", flagVistProjectInfo);
				// String
				// msgContent="您已成功注册SFA超级理财师账号，可使用当前手机号码和密码("+pwd+")登录超级理财师官网www.superfa.cn，如有疑问请电询4008558085";
				// log.info(msgContent);
				// try {
				// smsService.sendOtpMessage(registerDto.getMobile(),msgContent,Constants.regPasswdSmsAd);
				// } catch (Exception e) {
				// log.error("send regpasswdsmsadd error",e);
				// }
				user = userLogin;
			} else {
				user.setLoginName(loginName);
				// 判断活动传入 更新认证状态
				if (activityRole) {

					user.setuShoprole("2");
					;
					UserDTO up = new UserDTO();
					up.setuShoprole("2");
					up.setFpTempRole("1"); // 活动通过标识
					up.setLoginName(loginName);
					userService.updateUser(up);

					// 添加抽奖名单
					FpShopActivityUserDTO fsau = new FpShopActivityUserDTO();
					fsau.setMobile(loginName);
					int fsauNum = fpShopActivityUserService.queryListCount(fsau);
					if (fsauNum == 0) {
						fpShopActivityUserService.insert(fsau);
					}
				}
				user = userService.getUserByUF(user);

				result.setAttribute("isNewUser", isNewUser);
				
				if(!StringUtil.isNullOrEmptyNStr(sourceMobile)){
					UserDTO userSource = new UserDTO();
					userSource.setLoginName(sourceMobile);
					log.info("in doRegister SourceMobile :"+sourceMobile);
					userSource = userService.queryUserByMobile(userSource);
					
					user.setSourceCode(userSource.getId());//设置邀请人的id
					//自动分配  该用户名下
					Map<String,String> map=new HashMap<String, String>();
					userService.sysAutoAssign(user, map, user.getId());
				}
			}

			// 在设定时间内
			if (inputDate.before(d2) && inputDate.after(d1)
					&& (user.getRole() == null || !user.getRole().equals("2"))) {
				// 修改状态为通过
				UserDTO ud = new UserDTO();
				ud.setId(user.getId());
				ud.setuShoprole("2"); //
				ud.setFpTempRole("1"); // 活动通过标识
				user.setRole("2");
				ud.setLoginName(user.getLoginName());
				userService.updateUser(ud);
			}

			// 用户状态验证
			if (Constants.FA_STATUS_DISABLE.equals(user.getFaStatus())) {

				// 已经被禁用
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_ACCOUNT_DISABLE);
				result.setMessage("用户已经被禁用");
				return result;

			}
			// 用户状态验证
			if (Constants.FA_STATUS_BLACK.equals(user.getFaStatus())) {

				// 已经被禁用
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_ACCOUNT_BLACK);
				result.setMessage("用户已经被拉黑");
				return result;

			}

			Session session = getSession(true);
			session.setLogin(true);
			session.setUser(user);
			setSession(session);
			AuthenticationDTO auth = authenticationService.queryAuthInfo(user.getId());

			String returnUrl = (String) session.getAttribute("returnUrl");
			Map<String, Object> parameterMap = (Map<String, Object>) session.getAttribute("returnParameterMap");
			String returnMethod = (String) session.getAttribute("returnMethod");
			result.setAttribute("returnUrl", returnUrl);
			result.setAttribute("params", parameterMap);
			result.setAttribute("method", returnMethod);

			result.setAttribute("userType", user.getUType());
			result.setAttribute("uRole", user.getRole());
			result.setAttribute("uEmail", user.getuEmail());
			result.setAttribute("reviewStatus", "0");
			result.setAttribute("uRemark", user.getRemark());
			result.setAttribute("loginName", user.getLoginName());

			if (auth != null) {
				result.setAttribute("reviewStatus", auth.getReviewStatus());
				result.setAttribute("trade", auth.getTrade());
				result.setAttribute("tradeAge", auth.getTradeAge());
			}
			if (StringUtils.isBlank(user.getUserName())) {
				result.setAttribute("uName", "");
			} else {
				result.setAttribute("uName", user.getUserName());
			}

			if (StringUtils.isBlank(user.getuRealName())) {
				result.setAttribute("uRealName", "");
			} else {
				result.setAttribute("uRealName", user.getuRealName());
			}

			FaUserDTO userTmp = new FaUserDTO();
			userTmp.setId(user.getId());
			userTmp.setLastLoginIP(IPUtil.getRemoteHost(request));
			userTmp.setLastLoginTime(new Date());
			userTmp.setLoginNum(user.getLoginNum() + 1);

			userService.updateFaUserInfo(userTmp);

			result.setAttribute("id", user.getId());
			result.setAttribute("lastLoginIP", user.getLastLoginIP());
			result.setAttribute("lastLoginTime", user.getLastLoginTime());
			result.setAttribute("uImage", user.getuImage());

			// wap_jee_1.1 加入微信信息
			FaUserWechatDTO faUserWechatDTO = new FaUserWechatDTO();
			faUserWechatDTO.setUserId(user.getId());
			faUserWechatDTO = userWechatServiceImpl.queryUserWechatInfo(faUserWechatDTO);
			if (faUserWechatDTO != null) {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("headimgurl", faUserWechatDTO.getHeadimgurl());
				map.put("nickname", faUserWechatDTO.getNickname());
				result.setAttribute("faUserWechatDTO", map);
			}

			String pt = request.getParameter(Constants._PT);
			if (StringUtil.isMobilePT(pt)) {
				String token =  user.getId();
				try {
					String sessionId = request.getRequestedSessionId();
					token = SecureUtil.encrypt(token).replaceAll("=", "");
					Cookie cookie = new Cookie(Constants._TOKEN, token);
					cookie.setMaxAge(60 * 60 * 24 * 15);
					cookie.setPath("/");
					response.addCookie(cookie);
					// android
					result.setAttribute("token", token);
					result.setAttribute("phoneid", sessionId);
					MemcacheCacheHelper.mcc.set(token, System.currentTimeMillis());
				} catch (Exception e) {
					log.error("mobile pt create token error!", e);
				}
			}

			// 查询店主个人信息
			try {
				ShopperUserInfoDTO shopperUserInfo = new ShopperUserInfoDTO();
				// 用户id
				shopperUserInfo.setUserId(user.getId());
				ShopperUserInfoDTO shopperUserInfoDto = shopperUserInfoService.queryListGetFirst(shopperUserInfo);
				result.setAttribute("shopperUserInfoDto", shopperUserInfoDto);
			} catch (Exception e) {
				log.error("get ShopperUserInfoDTO error", e);
			}

			result.setStatus(STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setMessage("登陆成功");

		} catch (Exception e) {
			log.error("quickLogin error", e);
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		return result;
	}
}
